package com.zdj.data.net;

import com.zdj.app.AppConfig;
import com.zdj.utils.MD5;
import com.zdj.utils.MyLogUtil;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by zdj on 16-12-10.
 */

public class HeaderInteceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request original = chain.request();

        // Request customization: add request headers
        Request.Builder requestBuilder = original.newBuilder()
                .addHeader(AppConfig.AUTHORIZATION, AppConfig.BASIC)
                .addHeader("client","android")
                .addHeader("version","1.7.6");


        // 修改url路径
        int querySize = original.url().querySize();

        String url = original.url().scheme() + "://"  + original.url().url().getHost() + ":"+ original.url().port() + original.url().url().getPath();

        StringBuilder paramsStr = new StringBuilder();
        if(querySize == 0){
            paramsStr.append("signature=").append(MD5.getMD5Code("www.xingzhijishu.com"));
        }else{

            for (int i = 0; i < querySize; i++) {
                String queryName = original.url().queryParameterName(i);
                String queryValue = original.url().queryParameterValue(i);
                paramsStr.append(queryName).append("=").append(queryValue).append("&");
            }

            if(paramsStr.length() > 0){
                paramsStr.deleteCharAt(paramsStr.length() - 1); // 删除最后一个&字符
            }

            // 先 添加一个字符串生成md5码 ,然后删除该字符串,生成params
            paramsStr.append("www.xingzhijishu.com");
            String newValue = MD5.getMD5Code(paramsStr.toString());
            paramsStr.delete(paramsStr.lastIndexOf("www.xingzhijishu.com"),paramsStr.length());
            paramsStr.append("&signature=").append(newValue);
        }

        url += paramsStr.insert(0,"?").toString();

        Request request = requestBuilder.url(url).build();
        MyLogUtil.d("HeaderInteceptor", "intercept: \n" + request.toString());

        return chain.proceed(request);
    }
}
